<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat } from '@/hooks/util'
import * as accountApi from '@/api/account'
import * as questionQaApi from '@/api/questionQa'
import { message } from 'ant-design-vue'
import AddQA from './AddQA.vue'

const addQARef = ref()

let loading = ref<boolean>(false)
const dataSource = ref<Array<any>>([])
const columns = [
  {
    title: '全局调用标识ID',
    key: 'identifying',
    width: 150,
  },
  {
    title: '触发关键字',
    key: 'keyword',
    width: 150,
  },
  {
    title: '消息类型',
    key: 'replyType',
    width: 150,
  },
  {
    title: '消息内容',
    key: 'content',
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
  },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  // console.log('selectedRowKey=', selectedRowKeys)
  selectedRowKey.value = selectedRowKeys

  // console.log('selectedRow=', selectedRows)
  selectedRow.value = selectedRows
  sendData.value = selectedRow.value
  // console.log('sendData=', sendData.value)
}

const getList = async (robotId: string) => {
  loading.value = true
  try {
    let { state, data, message: msg } = await questionQaApi.getFishReplyList({ robotId })
    if (state === 200) {
      dataSource.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => {
  getRobatList()
  getGroupList()
})

const add = () => {
  addQARef.value.showModal()
}

const refreshList = (args: any) => {
  // console.log('args', args)
  if (args.flag) {
    dataSource.value = dataSource.value.map(item => {
      if (item.identifying == args.identifying) {
        item.identifying = args.identifying
        item.keyword = args.keyword
        item.replyType = args.type
        item.content = args.content
        item.updateTime = args.updateTime
        item.robotId = okRobat.value

        return item
      } else {
        return item
      }
    })
  } else {
    dataSource.value.push({
      identifying: args.identifying,
      keyword: args.keyword,
      replyType: args.type,
      content: args.content,
      createTime: args.createTime,
      updateTime: args.updateTime,
      robotId: okRobat.value,
    })
  }
}

// 删除
const del = (identifying: string) => {
  dataSource.value = dataSource.value.filter(item => item.identifying !== identifying)
}

// 修改
const edit = (record: any) => {
  addQARef.value.showModal(record)
}

// 拉取机器人列表
let okRobat = ref<string>()
import type { SelectProps } from 'ant-design-vue'
const robatList = ref<SelectProps['options']>([])
const options = ref<SelectProps['options']>([])
const groupList = ref<SelectProps['options']>([])
const groupId = ref<string>()
const getGroupList = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotGroupList()
    if (state === 200) {
      groupList.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectGroup = (selectValue: unknown) => {
  groupId.value = selectValue as string
  sendRobat.value = options.value
    .filter(item => item.groupId == groupId.value)
    .map(element => element.id)
}
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await accountApi.getFishRobotList({
      currentPage: 1,
      pageSize: 100,
    })
    if (state === 200) {
      robatList.value = data.list
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })

      options.value = data.list
      if (data.list.length == 0) {
        message.error('闲鱼：无平台账号，请先添加平台账号')
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  getList(okRobat.value)
}

// 推送配置
const sendData = ref<Array<any>>([])
let sendRobat = ref<Array<string>>()
const selectSendRobat = (selectValue: any) => {
  sendRobat.value = selectValue
  // console.log('sendRobat.value=', sendRobat.value)
}
const pushRobot = async () => {
  try {
    let { state, message: msg } = await questionQaApi.fishReplyPushArriveRobots({
      replyDtoList: dataSource.value,
      // pushRobotId: okRobat.value,
      receiveRobotIds: sendRobat.value,
    })
    if (state === 200) {
      message.success('推送成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const sendOk = () => pushRobot()

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}
</script>

<template>
  <!-- <page-container :title="route.meta.title"> -->
  <!-- <a-alert
      message="重要提醒"
      description="当前显示的为第一个账号的数据，如需加载指定账号数据请在右上角输入框进行选择微信账号/选择闲鱼账号操作！"
      type="warning"
      show-icon
      style="margin-bottom: 10px"
    /> -->
  <!-- <a-card style="overflow-x: scroll"> -->
  <!-- <a-tabs v-model:activeKey="activeKey"> -->
  <!-- <a-tab-pane key="1" tab="微信"> -->
  <div style="display: flex">
    <div style="flex: 1">
      <a-button type="primary" @click="add" style="margin-bottom: 10px; border-radius: 6px">
        添加智能问答
      </a-button>
    </div>
    <div>
      <span>选择闲鱼账号：</span>
      <a-select
        v-model:value="okRobat"
        @change="selectRobat"
        placeholder="请选择"
        style="width: 150px; text-align: left"
        show-search
        :options="optionList"
        :filter-option="filterOption"
      >
        <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
          {{ item.label }}
        </a-select-option>
      </a-select>
    </div>
  </div>
  <!-- -->
  <!-- :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }" -->

  <a-table
    style="overflow-x: scroll"
    :columns="columns"
    :data-source="dataSource"
    :pagination="false"
    :loading="loading"
    rowKey="identifying"
  >
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }">
      <template v-if="column.key === 'identifying'">
        <div style="width: 170px">
          <span>全局调用标识ID</span>
          <a-popover trigger="click">
            <template #content>
              <h3>
                <ExclamationCircleOutlined
                  style="color: #1890ff; font-size: 16px; margin-right: 5px"
                />
                全局调用标识ID
              </h3>
              <p style="width: 277px">
                <!-- 全部文案支持调用智能问答，  文案中变量使用方法为：[智能标识id问答]。 -->
                <br />
                例如：[bx98yxna9z]
              </p>
            </template>
            <span>
              <QuestionCircleOutlined
                style="color: #1890ff; font-size: 16px; margin-left: 5px; cursor: pointer"
              />
            </span>
          </a-popover>
        </div>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'identifying'">
        <div style="width: 150px">{{ record.identifying }}</div>
      </template>

      <template v-if="column.key === 'keyword'">
        <div style="width: 150px">{{ record.keyword }}</div>
      </template>

      <template v-if="column.key === 'replyType'">
        <div style="width: 150px" v-if="record.replyType == '1'">文本消息</div>
        <div style="width: 150px" v-if="record.replyType == '2'">图片</div>
      </template>

      <template v-if="column.key === 'content'">
        <div class="hiddenText" v-if="record.replyType == '1'">{{ record.content }}</div>
        <div v-if="record.replyType == '2'">
          <!-- <a :href="record.content" target="_blank">查看图片</a> -->
          <!-- <img :width="50" :src="record.content" /> -->

          <a-popover placement="rightTop">
            <template #content>
              <div class="popoverImg">
                <img :src="record.content" alt="" />
              </div>
            </template>
            <div class="imgBox">
              <img :src="record.content" alt="获取失败..." />
            </div>
          </a-popover>
        </div>
      </template>

      <template v-else-if="column.key === 'action'">
        <div style="width: 120px; margin: 0; padding: 0">
          <a @click="edit(record)">修改</a>
          <br />
          <a @click="del(record.identifying)">删除</a>
        </div>
      </template>
    </template>
  </a-table>

  <!-- 推送 -->
  <div style="margin: 5px 0">
    <span>选择推送闲鱼账号：</span>
    <a-select
      v-model:value="groupId"
      @change="selectGroup"
      placeholder="请选择分组"
      style="width: 6%; text-align: left"
    >
      <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
        {{ item.groupName }}
      </a-select-option>
    </a-select>
    <!-- <div style="width: 10px;"></div> -->
    <a-select
      mode="multiple"
      v-model:value="sendRobat"
      @change="selectSendRobat"
      allowClear
      placeholder="请选择店铺"
      style="width: 30%; text-align: left; margin-left: 5px"
      show-search
      :options="optionList"
      :filter-option="filterOption"
    >
      <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
    <a-button type="primary" style="margin-left: 10px; border-radius: 6px" @click="sendOk">
      确认推送
    </a-button>
  </div>

  <AddQA ref="addQARef" @refresh="refreshList"></AddQA>
  <!-- </a-tab-pane> -->
  <!-- <a-tab-pane key="2" tab="闲鱼" force-render>闲鱼</a-tab-pane> -->
  <!-- </a-tabs> -->
  <!-- </a-card> -->
  <!-- </page-container> -->
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 700px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

a:hover {
  color: red;
}

.imgBox {
  width: 80px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 500px;
  img {
    width: 100%;
  }
}
</style>
